package com.example.demo.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "demo.jwt")
public class JwtUtils {
    private long expire;
    private String secert;
    private String header;

    //生成jwt
    public String generateToken(String username){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire );
       return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(username)
                //现在的一个时间
                .setIssuedAt(nowDate)
                //过期时间
                .setExpiration(expireDate)

                .signWith(SignatureAlgorithm.HS512,secert)
                .compact();
    }
    //解析jwt
    public Claims getClaimsByToken(String jwt){
       try {
            return Jwts.parser()
                      .setSigningKey(secert)
                      .parseClaimsJws(jwt)
                      .getBody();
            } catch (Exception e) {
                return null;
       }
    }

    //jwt是否过期
     public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
     }




}
